<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;

use think\exception\ValidateException;
use think\facade\Log;

use util\Excel;
use think\facade\Db;
use think\cache\driver\Redis;

use util\Token;

use util\Upload;
/**
 * Querypurchase控制器
 */
class Querypurchasesku extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\ProcurementSku();

        $this->validate = \app\admin\validate\Querypurchasesku::class;
    }



    /**
     * 存疑采购成本
     * @param array params
     */
    public function index()
    {
        $thismonth=date('m');
        $thisyear=date('Y');
        if($thismonth==1){
            $lastmonth=12;
            $lastyear=$thisyear-1;
        }else{
            $lastmonth=$thismonth-1;
            $lastyear=$thisyear;
        }
        // if($thismonth==1){
        //     $lastmonth=11;
        //     $lastyear=$thisyear-1;
        // }elseif($thismonth==2){
        //     $lastmonth=12;
        //     $lastyear=$thisyear-1;
        // }else{
        //     $lastmonth=$thismonth-2;
        //     $lastyear=$thisyear;
        // }
        
        $token = $this->request->header('token');
            $admin = Token::admin($token);
            if(empty($admin)){
                return error('请重新登陆');
            }
        $redis = new Redis();
        $redis_month = $redis->get('change_monthsku-' . $admin['id']);
        if(!empty($redis_month)){
            $month= $redis_month;
        }else{
            $month= $lastyear . '-' . $lastmonth;
        }

        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        $where2 = array();
        //筛选日期
        if(!empty($filters['month']) && isset($filters['month'])){
            $where2['timedate'] = strtotime($filters['month']);
        }
        if(!empty($filters['number']) && isset($filters['number'])){
            $where2[] = ['number', 'LIKE', "%{$filters['number']}%"];
        }
        if(!empty($filters['sku']) && isset($filters['sku'])){
            $where2[] = ['sku', 'LIKE', "%{$filters['sku']}%"];
        }
            list($limit, $where, $sortArr) = $this->buildTableParames();
            $list = $this->model
                ->where($where2)
                ->order('id desc')
                ->paginate($limit);
            $lists = $list->items();
            foreach ($lists as $k=>$v) {
                $lists[$k]['add_time'] = date("Y-m-d H:i:s", $v['add_time']);
            }
            $data = [
                'code' => 1,
                'msg' => '',
                'count' => $list->total(),
                'data' => $lists,
                'start_time' => $month,
            ];
            return json($data);
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                $this->validate && validate($this->validate)->scene('edit')->check($post);
                //修改tags格式
                $post['updatetime'] = time();
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {
                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }

        return success('ok', $row);
    }
    
    /**
     * 导出
     */
    public function download_purchase()
    {
        $redis = new Redis();
        $start_time = input('start_time');
        if(!empty($start_time)){
            $month= $start_time;
            $start_time = $start_time."-1";
            $end_time = strtotime(date("Y-m-d", strtotime("$start_time +1 month")));
            $start_time=strtotime($start_time);//上个月的月初时间戳
        }else{
            $thismonth=date('m');
            $thisyear=date('Y');
            if($thismonth==1){
                $lastmonth=12;
                $lastyear=$thisyear-1;
            }else{
                $lastmonth=$thismonth-1;
                $lastyear=$thisyear;
            }
            // if($thismonth==1){
            //     $lastmonth=11;
            //     $lastyear=$thisyear-1;
            // }elseif($thismonth==2){
            //     $lastmonth=12;
            //     $lastyear=$thisyear-1;
            // }else{
            //     $lastmonth=$thismonth-2;
            //     $lastyear=$thisyear;
            // }
            $month= $lastyear . '-' . $lastmonth;
            $lastStartDay=$lastyear.'-'.$lastmonth.'-1';
            $lastEndDay=$lastyear.'-'.$lastmonth.'-'.date('t',strtotime($lastStartDay)).' 23:59:59';
            $start_time=strtotime($lastStartDay);//上个月的月初时间戳
            $end_time=strtotime($lastEndDay);//上个月的月末时间戳
        }

        $sql = "
            SELECT 
            b.sku
            FROM qu_order as a
            LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
            LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
            where 
            a.created_at >= ".$start_time."
            AND a.created_at <= ".$end_time."
            AND (financial_status = 'paid' or financial_status = 'partially_refunded' or financial_status = 'refunded' or financial_status = 'partially_paid')
            AND a.status = 'normal'
            GROUP BY b.sku
            ORDER BY b.sku desc";
        $list = Db::query($sql);
        $new_list = array();
        if(!empty($list)){
            foreach ($list as $k=>$v) {
                if(!empty($v['sku'])){
                    $pos = strpos($v['sku'], '-');
                    if($pos !== false){
                        $sku = explode('-',$v['sku']);
                        //数量
                        $km = count($sku) - 1;
                        $numeric = is_numeric($sku[$km]) ? true : false;
                        if($numeric){
                            //是数字并且小于100才计算数量
                            if($sku[$km] < 25){
                                $v['count'] = $sku[$km];
                            }else{
                                $v['count'] = 1;
                            }
                        }else{
                            $v['count'] = 1;
                        }
                        // 如果多颜色则数量乘以颜色数
                        foreach ($sku as $ksku=>$vsku) {
                            $possku = strpos($vsku, '+');
                            if($possku !== false){
                                $skujia = explode('+',$vsku);
                                $kmjia = count($skujia);
                                if($kmjia > 1){
                                    $v['count'] = $v['count'] * $kmjia;
                                    break;
                                }
                            }
                        }
                        $procurement_cost = $redis->get('procurement_cost-' . $sku[0]);
                        if(empty($procurement_cost)){
                            $procurement_cost = table('procurement_cost')->where('number',$sku[0])->order('timedate desc')->find();
                        }
                        if($procurement_cost){
                            $redis->set('procurement_cost-' . $sku[0], $procurement_cost, 60);
                            $v['number'] = $procurement_cost['number'];
                            $v['material'] = $procurement_cost['material'];
                            $v['zmaterial'] = (float)number_format((float)$procurement_cost['material'] * $v['count'], 3, '.', '');
                        }else{
                            $v['number'] = '请先上传品牌';
                            $v['material'] = 0;
                            $v['zmaterial'] = 0;
                        }
                        $v['month'] = $month;
                        $new_list[] = $v;
                    }
                }
            }
        }
        $header = array();

        $header[] = ['月份', 'month'];
        $header[] = ['编号', 'number'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['品牌成本￥(人名币)', 'material'];
        $header[] = ['单件数量', 'count'];
        $header[] = ['总成本', 'zmaterial'];

        $tableName = '本月SKU成本';
        $fileName = "export_" . $tableName . "_" . time();
        return Excel::exportData($new_list, $header, $fileName, 'xls');
            
    }

    
    /**
     * 上传文件
     */
    public function uploads()
    {
        $file = $this->request->file('file');
        // try {
        $upload = new Upload();
        $res = $upload->upload($file);
        if ($res['url']) {
            // return success('ok', $res['url']);
            $return = $this->import_cost($res['url']);
            return success('ok', $return);
        } else {
            return error($res['msg']);
        }
        // } catch (\Exception $e) {
        //     Log::error("---ajax---upload--error:" . $e);
        // }
        return error('上传文件失败');
    }

    //导入花费
    public function import_cost($url)
    {
        $url_arr = explode('storage/', $url);
        $data = Excel::import('storage/' . $url_arr[1]);
        unset($data[1]);
        $arr_insert = array();
        foreach ($data as  $value) {
            $arr_insert[] = [
                'month' => isset($value[0]) ? $value[0] : 0,
                'number' => isset($value[1]) ? $value[1] : 0,
                'sku' => isset($value[2]) ? $value[2] : '',
                'material' => isset($value[3]) ? $value[3] : '',
                'count' => isset($value[4]) ? $value[4] : '',
                'zmaterial' => isset($value[5]) ? $value[5] : '',
                'timedate' => strtotime($value[0]),
                'add_time' => time(),
            ];
        }
        if(!empty($arr_insert)){
            table('procurement_sku')
            ->where('month',$arr_insert[0]['month'])
            ->delete();
            table('procurement_sku')->insertAll($arr_insert);
        }
        return $url;
    }

    /**
     * 修改月份
     *
     */
    public function change_month()
    {
        $post = $this->request->post();
        if(!empty($post['start_time']) && isset($post['start_time'])){
            $start_time = strtotime($post['start_time']);
            $start_time = date('Y-m', $start_time);
            $token = $this->request->header('token');
            $admin = Token::admin($token);
            if(empty($admin)){
                return error('请重新登陆');
            }
            $redis = new Redis();
            $redis->set('change_monthsku-'.$admin['id'], $start_time, 60 * 60);

            return success('切换成功');
        }else{
            return error('请填写切换的月份');
        }
    }
}
